package org.eliza.rpc.rpc


import io.ktor.client.*
import io.ktor.http.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.runBlocking
import kotlinx.rpc.krpc.ktor.client.installKrpc
import kotlinx.rpc.krpc.ktor.client.rpc
import kotlinx.rpc.krpc.ktor.client.rpcConfig
import kotlinx.rpc.krpc.serialization.json.json
import kotlinx.rpc.krpc.streamScoped
import kotlinx.rpc.withService
import org.eliza.rpc.rpc.model.AwesomeService

fun main() = runBlocking {
    val ktorClient = HttpClient {
        installKrpc()
    }

    val client = ktorClient.rpc {
        url {
            host = "0.0.0.0"
            port = 8080
            encodedPath = "awesome"
        }

        rpcConfig {
            serialization {
                json()
            }
        }
    }

    val recognizer: AwesomeService = client.withService<AwesomeService>()

    streamScoped{
        val news = recognizer.getNews("xxxxcity")
        news.flowOn(Dispatchers.IO).collect {
            println(it)
        }
    }

    recognizer.cancel()
    ktorClient.close()
}